<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_job_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['submit:task:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column label="任务ID" align="center" prop="taskId" /> -->
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务启用日期" align="center" prop="activeDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.activeDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务终止日期" align="center" prop="expiryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="taskStatus">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.taskStatus"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="任务负责人" align="center" prop="taskManager">
        <!-- 从UserList翻译 -->
        <template slot-scope="scope">  
          <!-- 使用作用域插槽渲染内容 -->  
          <span>  
            {{ getNickName(scope.row) }}  
          </span>  
        </template> 
      </el-table-column>
      <el-table-column label="压缩类型" align="center" prop="compressType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.submit_task_compress_type" :value="scope.row.compressType"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['submit:task:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['submit:task:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报送任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="启用日期" prop="activeDate">
              <el-date-picker clearable
                v-model="form.activeDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择任务启用日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终止日期" prop="expiryDate">
              <el-date-picker clearable
                v-model="form.expiryDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择任务终止日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="时间配置" prop="timeConfig">
          <timeConfig 
          @timeConfigJsonChanged="handleTimeConfigJsonChange"
           :innerTimeConfig="form.timeConfig">
          </timeConfig>
        </el-form-item>
        <el-form-item label="接口" prop="interfaceIds">
          <el-select v-model="selectedInterfaces" multiple placeholder="请选择接口">
            <el-option
              v-for="item in interfaceList"
              :key="item.interfaceId"
              :label="item.interfaceCnName"
              :value="item.interfaceId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务负责人" prop="taskManager">
          <el-select v-model="form.taskManager" placeholder="请选择任务负责人">
            <el-option
              v-for="user in userList"
              :key="user.userId"
              :label="user.nickName"
              :value="user.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="压缩类型" prop="compressType">
              <el-select v-model="form.compressType" placeholder="请选择压缩类型">
                <el-option
                  v-for="dict in dict.type.submit_task_compress_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="压缩包名称" prop="compressName">
              <el-input v-model="form.compressName" placeholder="请输入压缩包名称" :disabled="form.compressType !== '1'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="任务描述" prop="taskDesc">
          <el-input v-model="form.taskDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask,updateStatus } from "@/api/submit/task";
import { listUser } from "@/api/system/user";
import timeConfig from "./timeConfig.vue";
import { listInterface} from "@/api/submit/interface";


export default {
  name: "Task",
  dicts: ['sys_job_status', 'submit_task_compress_type'],
  components: { timeConfig: timeConfig },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报送任务表格数据
      taskList: [],
      // 用户信息查询列表
      userList: [],
      // 用户选择的接口列表
      selectedInterfaces: [],
      //接口列表
      interfaceList: [],
      // 日期范围
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        activeDate: null,
        expiryDate: null,
        taskStatus: null,
        taskManager: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskName: [
          { required: true, message: "任务名称不能为空", trigger: "blur" }
        ],
        activeDate: [
          { required: true, message: "任务启用日期不能为空", trigger: "blur" }
        ],
        expiryDate: [
          // { required: true, message: "任务终止日期不能为空", trigger: "blur" }
        ],
        taskStatus: [
          // { required: true, message: "任务状态不能为空", trigger: "change" }
        ],
        interfaceIds: [
          { required: true, message: "接口不能为空", trigger: "blur" }
        ],
        taskManager: [
          { required: true, message: "任务负责人不能为空", trigger: "blur" }
        ],
        compressType: [
          { required: true, message: "压缩类型不能为空", trigger: "change" }
        ],
        timeConfig: [
          { required: true, message: "时间配置不能为空", trigger: "change" }
        ],
      },
      submitInterfaceListVo:{
        reportTimeConfig: null
      }
    };
  },
  created() {
    this.getUserList();
    this.getList();
  },
  methods: {
    /** 查询报送任务列表 */
    getList() {
      this.loading = true;
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // 重置表单
      this.form = {
        taskId: null,
        taskName: null,
        activeDate: null,
        expiryDate: null,
        taskStatus: null,
        interfaceIds: null,
        jobId: null,
        taskManager: null,
        taskDesc: null,
        compressType: null,
        compressName: null,
        createId: null,
        createTime: null,
        updateId: null,
        updateTime: null
      };
      this.resetForm("form");
      // 重置submitInterfaceListVo
      this.submitInterfaceListVo.reportTimeConfig = null;
      // 重置提交接口列表
      this.selectedInterfaces = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fetcSelectList();
      this.open = true;
      this.title = "添加报送任务";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if(row.taskStatus === '0'){
        this.$modal.msgError("任务正在运行，不允许修改！");
      }else{
        this.reset();
        this.fetcSelectList();
        const taskId = row.taskId || this.ids
        getTask(taskId).then(response => {
          //给表单赋值
          this.form = response.data;
          //将interfaceIds赋值给selectedInterfaces
          this.selectedInterfaces = response.data.interfaceIds.split(",").map(Number);
          this.open = true;
          this.title = "修改报送任务";
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.taskId != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if(row.taskStatus === '0'){
        this.$modal.msgWarn("任务正在运行，不允许删除！");
      }else{
        const taskIds = row.taskId || this.ids;
        this.$modal.confirm('是否确认删除报送任务编号为"' + taskIds + '"的数据项？').then(function() {
          return delTask(taskIds);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      }
      
    },
    fetcSelectList() {
      // 查询接口信息
      listInterface(this.submitInterfaceListVo).then(response => {
        this.interfaceList = response.rows;
      });
    },
    // 查询用户信息
    getUserList() {
      listUser().then(response => {
        this.userList = response.rows;
      });
    },
    // 时间配置json改变
    handleTimeConfigJsonChange(newTimeConfigJson) {
      // 将新的timeConfigJson赋值给form对象
      this.form.timeConfig = newTimeConfigJson;
      // console.log(this.form.timeConfig);
      //清空所选接口
      this.selectedInterfaces = [];
      // 更新接口信息
      this.submitInterfaceListVo.reportTimeConfig = newTimeConfigJson;
      listInterface(this.submitInterfaceListVo).then(response => {
        this.interfaceList = response.rows;
      });
    },
    handleStatusChange(row){
      let text = row.status === '0' ? '启用' : '停用';
      this.$modal.confirm('确认要' + text + '此任务吗？').then(function() {
        return updateStatus(row.taskId);
      }).then(response => {
        if(response.code === 200){
          this.getList();
          this.$modal.msgSuccess(response.msg);
        }else{
          this.getList();
          this.$modal.msgError(response.msg);
        }
      });
    },
    getNickName(row){
      const userId = row.taskManager;
      const user = this.userList.find(user => user.userId === userId);  
      return user ? user.nickName : '未知'; 
    }
  },
  watch: {
    selectedInterfaces: function(newSelectedInterfaces) {
      if (newSelectedInterfaces.length === 1) {
        this.form.interfaceIds = newSelectedInterfaces[0]; // 如果只选择了一个接口，则将 interfaceIds 设置为该接口的 id
      } else if (newSelectedInterfaces.length > 1) {
        this.form.interfaceIds = newSelectedInterfaces.join(','); // 如果选择了多个接口，则用英文逗号隔开
      } else {
        this.form.interfaceIds = ''; // 如果没有选择接口，则将 interfaceIds 设置为空字符串
      }
    },
  }
};
</script>
